package com.Socket;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import net.sf.json.JSONObject;

@ServerEndpoint("/websocket/{username}")
public class WebSocket {

	private static int onlineCount = 0;
	private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
	private static List<String> list = new ArrayList<String>();
	private Session session;
	private JSONObject json;
	private String username;
	private String img="111.jpg";

	@OnOpen
	public void onOpen(@PathParam("username") String username, Session session) throws IOException {

		this.username = username;
		this.session = session;
		addOnlineCount();
		list.add(username);
		json = new JSONObject();
		json.element("onlineCount", getOnlineCount());
		json.element("img", img);
		json.element("onstatus", 1);
		json.element("list", list);
		json.element("username", username);
		json.element("To", "All");
		clients.put(username, this);
		sendMessageAll(json.toString());
		json.element("onstatus", 0);
	}

	@OnClose
	public void onClose() throws IOException {
		json.element("onstatus", -1);
		list.remove(username);
		clients.remove(username);
		subOnlineCount();
		json.element("onlineCount", getOnlineCount());
		json.element("list", list);
		json.element("To", "All");
		sendMessageAll(json.toString());
	}

	@OnMessage
	public void onMessage(String message) throws IOException {

		JSONObject jsonTo = JSONObject.fromObject(message);
		json.element("message", jsonTo.get("message"));
		
		if (!jsonTo.get("To").equals("All")){
			json.element("To", "One");
			sendMessageTo(json.toString(), jsonTo.get("To").toString());
		}else{
			json.element("To", "All");
			sendMessageAll(json.toString());
		}
	}

	@OnError
	public void onError(Session session, Throwable error) {
		error.printStackTrace();
	}

	public void sendMessageTo(String message, String To) throws IOException {
		// session.getBasicRemote().sendText(message);
		//session.getAsyncRemote().sendText(message);
		for (WebSocket item : clients.values()) {
			if (item.username.equals(To) )
				item.session.getAsyncRemote().sendText(message);
		}
	}
	
	public void sendMessageAll(String message) throws IOException {
		for (WebSocket item : clients.values()) {
			item.session.getAsyncRemote().sendText(message);
		}
	}
	
	

	public static synchronized int getOnlineCount() {
		return onlineCount;
	}

	public static synchronized void addOnlineCount() {
		WebSocket.onlineCount++;
	}

	public static synchronized void subOnlineCount() {
		WebSocket.onlineCount--;
	}

	public static synchronized Map<String, WebSocket> getClients() {
		return clients;
	}
}
